package com.mashibing.test.singleton;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author: mayu
 * @date: 2021年05月18日 16:36
 * 懒汉式
 * synchronized 3 DCL
 * 对象创建的3步：
 * ①使用new在堆内申请一块内存，得到一个半初始化对象
 * ②调用构造方法，初始化对象
 * ③设置关联，将引用和对象进行关联
 */
public class S5 {
    //volatile修饰，避免指令重排可能造成的NPE问题
    private volatile static S5 INSTANCE = null;

    private S5() {
    }

    public static S5 getInstance() {
        if (INSTANCE == null) {
            synchronized (S5.class) {
                if (INSTANCE == null) {
                    try {
                        TimeUnit.MILLISECONDS.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    INSTANCE = new S5();
                }
            }
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        CountDownLatch cdl = new CountDownLatch(1000);

        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "：" + S5.getInstance().hashCode());
                cdl.countDown();
            }).start();
        }

        try {
            cdl.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("执行耗时：" + (end - start));//341
    }
}
